package com.lill.workflow.web;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.lill.common.component.util.PageUtils;
import com.lill.common.component.util.Query;
import com.lill.common.component.util.R;
import com.lill.org.service.ICompanyBranchService;
import com.lill.support.annotation.CurrentUser;
import com.lill.system.constant.SystemConstant;
import com.lill.system.model.SysUserEntity;
import com.lill.workflow.constant.BusinessType;
import com.lill.workflow.model.WorkflowEmployeeModel;
import com.lill.workflow.model.WorkflowInfoModel;
import com.lill.workflow.service.IWorkflowInfoService;

/**
 * Controller
 *
 * @author lill
 * @date 2019-05-26 12:05:20
 */
@RestController
@RequestMapping("workflow/info")
public class WorkflowInfoController {
    @Autowired
    private IWorkflowInfoService workflowInfoService;
    @Autowired
    private ICompanyBranchService branchService;

    /**
     * 查看列表
     */
    @RequestMapping("/list")
    //@RequiresPermissions("workflowP:info:list")
    public R list(@RequestParam Map<String, Object> params,@CurrentUser SysUserEntity curUser) {
    	if (!SystemConstant.SUPER_ADMIN.equals(curUser.getId())) {
    		params.put("companyId", curUser.getCompanyId());
    		Map<String, Object> branchInfo=branchService.queryUserFirstBranch(curUser.getDepartId());
    		if(null!=branchInfo){
    			params.put("branchId",curUser.getBranchId());
    		}else{
    			params.put("regionId",curUser.getDepartId());
    		}
    	}
        //查询列表数据
        Query query = new Query(params);

        List<WorkflowInfoModel> workflowInfoList = workflowInfoService.queryList(query);
        int total = workflowInfoService.queryTotal(query);
        PageUtils pageUtil = new PageUtils(workflowInfoList, total, query.getLimit(), query.getPage());

        return R.ok().put("page", pageUtil);
    }

    /**
     * 查看列表
     */
    @RequestMapping("/querySelect")
    //@RequiresPermissions("workflowP:info:list")
    public R querySelect(@RequestParam Map<String, Object> params,@CurrentUser SysUserEntity curUser) {
        if (!SystemConstant.SUPER_ADMIN.equals(curUser.getId())) {
            params.put("companyId", curUser.getCompanyId());
            params.put("branchId",curUser.getBranchId());
            params.put("onlyOne","one");
        }
        if(!params.containsKey("departId")||null==params.get("departId")||StringUtils.isEmpty(params.get("departId").toString())){
        	params.put("departId",curUser.getDepartId());
        }
        
        params.put("status",1);
        List<WorkflowInfoModel> workflowInfoList = workflowInfoService.queryList(params);
        return R.ok().put("list", workflowInfoList);
    }
    
    @RequestMapping("/querySelectByOther")
    //@RequiresPermissions("workflowP:info:list")
    public R querySelectByOther(@RequestParam Map<String, Object> params,@CurrentUser SysUserEntity curUser) {
        List<WorkflowInfoModel> workflowInfoList =null;
        if (!SystemConstant.SUPER_ADMIN.equals(curUser.getId())) {
            params.put("companyId", curUser.getCompanyId());
            if(curUser.getBranchId()!=null){
                params.put("branchId",curUser.getBranchId());
                workflowInfoList= workflowInfoService.queryList(params);
            }else {
                workflowInfoList= workflowInfoService.queryListByOther(params);
            }

        }
        return R.ok().put("list", workflowInfoList);
    }

    /**
     * 查看信息
     */
    @RequestMapping("/info/{id}")
    //@RequiresPermissions("workflow:info:info")
    public R info(@PathVariable("id") String id) {
    	WorkflowInfoModel workflowInfo = workflowInfoService.queryObject(id);

        return R.ok().put("workflowInfo", workflowInfo);
    }
    @RequestMapping("/currentSumInfo/{id}")
    //@RequiresPermissions("workflow:info:info")
    public R currentSumInfo(@PathVariable("id") String id) {
        int sum = workflowInfoService.selectCurrentSum(id);
        if(sum>3){
             sum=3;
        }
        return R.ok().put("sum", sum);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody WorkflowInfoModel workflowInfo,@CurrentUser SysUserEntity user) {
    	if(StringUtils.isNotEmpty(workflowInfo.getDepartId())){
    		workflowInfo.setCompanyId(user.getCompanyId());
    		Map<String, Object> branchInfo=branchService.queryUserFirstBranch(workflowInfo.getDepartId());
    		if(null!=branchInfo){
    			workflowInfo.setBranchId(branchInfo.get("branch_id")+"");
    		}
    	}else{
    		return R.error("当前流程所属部门不能为空！");
    	}
    	
//    	workflowInfo.setBranchId(user.getBranchId());
        // 先查询当前公司有没有购车流程
        Map<String,Object>map = new HashMap<>();
        map.put("companyId",workflowInfo.getCompanyId());
        map.put("branchId",workflowInfo.getBranchId());
        map.put("departId",workflowInfo.getDepartId());
        map.put("code",workflowInfo.getCode());
        map.put("status",1);
        List<WorkflowInfoModel> workflowInfoModels = workflowInfoService.queryList(map);
        boolean hasRepeat=false;
        if (workflowInfoModels != null && workflowInfoModels.size() > 0 ) {
        	hasRepeat=true;
        	
        	switch (workflowInfo.getLevelData()) {
				case "company":hasRepeat=false;break;
				case "region":
					for (WorkflowInfoModel workflowVo : workflowInfoModels) {
						if(workflowVo.getLevelData().equals("region")||workflowVo.getLevelData().equals("company")){
							hasRepeat=true;break;
						}
					}
					break;
				case "branch":hasRepeat=true;break;
				default:break;
			}
        	if(hasRepeat){
        		return R.error("当前流程所属部门已经有该类型流程，不能重复提交");
        	}
        }
        List<WorkflowEmployeeModel> auditEmployeeList=workflowInfo.getAuditEmployeeList();
        if (auditEmployeeList == null || auditEmployeeList.isEmpty() || auditEmployeeList.size() ==0 ) {
            return R.error("请添加审核人");
        }
//      workflowInfo.setCompanyId(user.getCompanyId());
//    	workflowInfo.setBranchId(user.getBranchId());
//    	workflowInfo.setDepartId(user.getDepartId());
        workflowInfo.setName(BusinessType.getContent(workflowInfo.getCode()));
    	workflowInfo.setStatus(1);
    	workflowInfo.setCreateUser(user.getId());
    	workflowInfo.setCreateTime(new Date());
        int result=workflowInfoService.save(workflowInfo,hasRepeat);
		if(result>0){
        	return R.ok();
        }else{
        	return R.error("当前流程所属部门已经存在该审核流程");
        }
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    //@RequiresPermissions("workflow:info:update")
    public R update(@RequestBody WorkflowInfoModel workflowInfo,@CurrentUser SysUserEntity user) {
    	workflowInfo.setUpdateUser(user.getId());
    	workflowInfo.setUpdateTime(new Date());
        int result=workflowInfoService.update(workflowInfo);
		if(result>0){
        	return R.ok();
        }else{
        	return R.failure();
        }
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    //@RequiresPermissions("workflow:info:delete")
    public R delete(@RequestBody String[] ids,@CurrentUser SysUserEntity user) {
    	Map<String, Object> params=new HashMap<String, Object>();
    	params.put("ids", ids);
    	params.put("updateUser", user.getId());
    	params.put("updateTime", new Date());
    	
        int result=workflowInfoService.deleteLogicByMap(params);
		if(result>0){
        	return R.ok();
        }else{
        	return R.failure();
        }
    }

    /**
     * 查看所有列表
     */
    @RequestMapping("/queryAll")
    public R queryAll(@RequestParam Map<String, Object> params,@CurrentUser SysUserEntity curUser) {
    	if (!SystemConstant.SUPER_ADMIN.equals(curUser.getId())) {
    		params.put("companyId", curUser.getCompanyId());
    	}

        List<WorkflowInfoModel> list = workflowInfoService.queryList(params);

        return R.ok().put("list", list);
    }
    /**
     * 获取流程枚举
     */
    @RequestMapping("/getBusinessType")
    public R getBusinessType() {
        return R.ok().put("list", BusinessType.getList());
    }

    /**
     * 根据流程编码查询所有审核人
     */
    @RequestMapping("/querySteps")
    public R querySteps(@RequestParam Map<String, Object> params,@CurrentUser SysUserEntity curUser) {
        // 如果不是超级管理员，则只能查询本部门及子部门数据
        if (!SystemConstant.SUPER_ADMIN.equals(curUser.getId())) {
            //branchId不为空   代表公司
            if (curUser.getBranchId() != null && !"".equals(curUser.getBranchId())) {
                params.put("branchId",curUser.getBranchId());
            }
            params.put("companyId", curUser.getCompanyId());
        }
        List<WorkflowEmployeeModel> list = workflowInfoService.querySteps(params);

        return R.ok().put("list", list);
    }
}
